package zhqs;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 * 组播接收程序
 */
public class MuiltcastReceiver {

    public static void main(String[] args) {
        try {
            String muiltcastip = "224.0.0.50";
            int muiltcastport = 9898;
            MulticastSocket multicastSocket = new MulticastSocket(muiltcastport);// 创建组播套接字并绑定到发送端口
            InetAddress inetAddress = InetAddress.getByName(muiltcastip);
            multicastSocket.joinGroup(inetAddress);// 组播套接字加入组播组

            while (true) {
                System.out.println("===========>>>>>>  准备接收组播数据...    当前监听 " + muiltcastip + " " + muiltcastport);
                
                byte[] data = new byte[1024];
                DatagramPacket datagramPacket = new DatagramPacket(data, data.length);// 创建一个用于接收数据的数据包
                multicastSocket.receive(datagramPacket);// 接收数据包
                
                String ip = datagramPacket.getAddress().getHostAddress();
                int port = datagramPacket.getPort();
                
                System.out.println(new String(data) + "   " + ip + "   " + port);
                
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}